package com.lagou;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author godai
 * @date 2021/1/31 13:21
 * @description
 */
public class RpcEncoder extends MessageToByteEncoder<Object> {
    private Class<?> clazz;
    private Serializer serializer;


    public RpcEncoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {
        if (clazz != null && clazz.isInstance(msg)) {
            byte[] className = msg.getClass().getName().getBytes();
            byte[] classData = serializer.serialize(msg);

            byteBuf.writeInt(className.length);
            byteBuf.writeInt(classData.length);

            byteBuf.writeBytes(className);
            byteBuf.writeBytes(classData);
        }
    }

}


